import request from '../../utils/request'
Page({
    data: {
        signId: null,
        userList: [],
        currentUser: null
    },

    onLoad: function (options) {
        if (options.signId) {
            this.setData({
                signId: options.signId
            });
        }
        this.getDataAndUpdateStatus();
    },

    getDataAndUpdateStatus() {
        request({
            url: 'contractlog/contractlog/list',
            method: 'GET',
            data:{pageNum:1,pageSize:1000000},
            success: (res) => {
                console.log(res.data.rows);
                const userId = wx.getStorageSync('userid');
                console.log(userId);


                // 查找匹配的用户
                const matchedUser = res.data.rows.find(item => item.userId === userId);
                if (matchedUser) {
                    console.log(matchedUser.id);
                    this.setData({
                        currentUser: matchedUser
                    });
                    // 根据匹配用户的 id 更新用户签约状态为 3（支付成功）
                    this.updateUserStatus(matchedUser.id);
                } else {
                    console.log('未找到匹配的用户');
                    wx.showToast({
                        title: '未找到匹配用户',
                        icon: 'none'
                    });
                }
            },
            fail: (err) => {
                console.log('获取用户列表失败', err);
                wx.showToast({
                    title: '获取用户列表失败',
                    icon: 'none'
                });
            }
        });
    },

    // 更新用户签约状态为 3（支付成功）
    updateUserStatus(id) {
        const userId = wx.getStorageSync('userid');
        request({
            url: 'contractlog/contractlog',
            method: 'PUT',
            data: {
                id: id,
                userId: userId, // 添加 userId 字段
                status: 3 // 设置为支付成功状态
            },
            success: (res) => {
                console.log('用户签约状态更新成功');
                // 显示成功提示
                wx.showToast({
                    title: '支付成功',
                    icon: 'success',
                    duration: 2000
                });
            },
            fail: (err) => {
                console.log('更新用户签约状态失败', err);
                wx.showToast({
                    title: '更新用户签约状态失败',
                    icon: 'none'
                });
            }
        });
    },

    viewSignDetail: function () {
        console.log(this.data);
        wx.redirectTo({
            url: `/pages/signdetail/signdetail?id=${this.data.currentUser.id}&status=${this.data.currentUser.status}`
        });
    },

    backToHome: function () {
        wx.switchTab({
            url: '/pages/index/index'
        });
    }
})